var acttoolv2 = require('../../sys/toolv2')
var locationclient = require('../../sys/locationclient')
var locationhelper = require('../../sys/locationhelper')
Component({
  options: {
    addGlobalClass: true,
    multipleSlots: true
  },
  /**
   * 组件的属性列表
   */
  properties: {
    themcolor: {
      type: Object
    }

  },

  /**
   * 组件的初始数据
   */
  data: {
    distance: null,
    searchkey: "",
    selectidx: 0,
    polylines: [],
    mapinitstatus: -1,
    isoping: false,

    latitude: '39.92556',
    longitude: '116.434739',
    CustomBar: 64,
    isshow: false,
    circles: [],
    iconmarker: "",
    // circles: [{
    //   latitude: '23.099994',
    //   longitude: '113.324520',
    //   color: '#FF0000DD',
    //   fillColor: '#7cb5ec88',
    //   radius: 400,
    //   strokeWidth: 2
    // }],
    mode: 1,
    markers: [], 
    addrlist: [],
    mapCtx: null
  },


  ready() {
      var app = getApp();
    this.setData({ CustomBar: app.globalData.CustomBar })
    var eg = app.globalData.configdata.eg;
    this.data.iconmarker = eg.basicelink + eg.location.iconmarker
  },

  /**
   * 组件的方法列表
   */
  methods: {

    getcirclemodel(lat, lng, radius) {

      return {
        latitude: lat,
        longitude: lng,
        color: '#FF0000DD',
        fillColor: '#7cb5ec22',
        radius: parseInt(radius),
        strokeWidth: 2
      }
    },
    getempmark(id, lat, lng) {
      var iconPath = ""
      var exattr = {}
      // if (id == 2) {
      //   exattr = {}
      //   if (this.data.iconmarker) {

      //     exattr["iconPath"] = this.data.iconmarker
      //   }


      // }
      return {
        id: id,
        latitude: lat,
        longitude: lng,
        name: '',
        ...exattr

      };
    },
    Backfunc() {

    var markers=  this.data.markers
    if(markers && markers.length>0)
    {
      var ids =[];
      markers.forEach(item=>{

        ids.push(item.id);
      })

  

      this.getmapCtx().removeMarkers({markerIds:ids})
    }
    
    
      this.setData({ isshow: false,polylines:[],markers:[],addrlist:[],circles:[] })   
    },


    stopreginchange(vtime) {
      var that = this;
      if (!vtime) {
        vtime = 100
      }
      that.data.isoping = true
      setTimeout(() => {
        that.data.isoping = false
      }, vtime);
    },



    /**
     * 
     * @param {*} model  1普通地址 2范围的地图
     * @param {*} addrmodel 
     */
    showmap(mode, addrmodel, intracity) {
      if (mode == 2) {
        intracity.lat = parseFloat(intracity.lat)
        intracity.lng = parseFloat(intracity.lng)
        this.loadcircle(intracity);
        this.setData({ intracity })
      }
      this.data.mode = mode
      if (addrmodel.lat && addrmodel.lat != 0) {

        var ad_info = { province: addrmodel["province"], city: addrmodel["city"], district: addrmodel["county"] }
        var newobj = { address: addrmodel["addrinfo"], title: addrmodel["addrname"], lat: addrmodel.lat, lng: addrmodel.lng, ad_info }
        this.getaddrlist(newobj)
        this.movemark(2, addrmodel.lat, addrmodel.lng)
        this.setData({ latitude: addrmodel.lat, longitude: addrmodel.lng })

      }
      else if (addrmodel.addrinfo) {

        if (addrmodel.addrinfo.indexOf(addrmodel.county) == -1) {
          addrmodel.addrinfo = addrmodel.county + addrmodel.addrinfo
        }

        this.setData({ searchkey: addrmodel.addrinfo })
        this.onSearch();

      }
      else {


        this.getnowlat();
      }

      this.setData({ isshow: true, mode })

      return;


    },
    regionchange(ev) {

      if (this.data.isoping == true) {

        return;
      }

      if (ev.type == "end") {
        if (ev.detail) {
          var centerLocation = ev.detail.centerLocation

          var mode = this.data.mode;
          if (mode == 2) {

          
            this.updatepolylines(centerLocation.latitude, centerLocation.longitude, 2)
          }
          else {

            this.movemark(2, centerLocation.latitude, centerLocation.longitude)

            this.getaddrlist({ lat: centerLocation["latitude"], lng: centerLocation["longitude"] })

          }

        }
      }

    },

    getmapCtx() {
      if (!this.data.mapCtx) {
        var that = this
        this.data.mapCtx = wx.createMapContext('myMap', that)
      }
      return this.data.mapCtx;
    },
    movemark(id, lat, lng) {
      var markers = this.data.markers;
      var marker = this.getempmark(id, lat, lng)

    
      var index = markers.findIndex(item => { return item.id == id })
      if (index < 0) {
        markers.push(marker)
      }
      else {
        markers.splice(index, 1, marker)
      }

      this.getmapCtx().addMarkers({
        markers, clear: true, complete(ecomplete) {
        

        }
      })

     
    },
    getnowlat() {
      var that = this;
      that.data.isoping = true


      locationhelper.location().then(function (reslut) {
        if (reslut["status"] == 1) {
          var res = reslut.position;

          if (that.data.mode == 2) {
            that.updatepolylines(res["lat"], res["lng"], 2)
          }
          else {

            that.movemark(2, res["lat"], res["lng"]);
            that.getaddrlist({ lat: res["lat"], lng: res["lng"] })
          }
          that.setData({ latitude: res["lat"], longitude: res["lng"] })
        }
        setTimeout(() => {
          that.data.isoping = false
        }, 100);
      })


    },
    maptap(ev) {
      var that = this
      var res = ev.detail;
      if (that.data.mode == 2) {

          
        this.updatepolylines(res.latitude, res.longitude, 2)
      }
      else
      {
        that.movemark(2, res["latitude"], res["longitude"]);
        that.getaddrlist({ lat: res["latitude"], lng: res["longitude"] })
      }
  
    },
    getaddrlist(loaction) {
      var that = this;
      locationclient.locationaddr(loaction).then(function (data) {
        var selectaddr = {}

        if (loaction.addrinfo) {
          selectaddr = data["raw"]
          selectaddr["title"] = loaction.addrname
          selectaddr["address"] = loaction.addrinfo
          selectaddr["location"] = { lat: loaction.lat, lng: loaction.lng }
          //  province city county
        }
        else {
          selectaddr = data["raw"]
          selectaddr["title"] = data["raw"]["formatted_addresses"]["recommend"]
          selectaddr["address"] = data["raw"]["formatted_addresses"]["rough"]
        }

        var addrlist = [selectaddr, ...data.pois]
        var distance = null
        if (that.data.mode == 2) {
          var intracity = that.data.intracity
          distance = acttoolv2.distanceByLnglat(selectaddr.location.lng, selectaddr.location.lat, intracity.lng, intracity.lat)
        }

        that.setData({ addrlist: addrlist, selectidx: 0, distance })

      })
    },

    updatepolylines(lat, lng, id, updateaddr) {
      this.data.polylines[0]["points"][1]["latitude"] = lat
      this.data.polylines[0]["points"][1]["longitude"] = lng

      if (!id) {
        id = 2
      }
      var markers = this.data.markers;
      var hasmarker = markers.find(item => {
        return item.id == id
      })
      if (hasmarker) {
        var len = markers.length;
        for (var i = 0; i < len; i++) {
          if (markers[i].id == id) {
            markers[i]["latitude"] = lat
            markers[i]["longitude"] = lng
          }
        }
      }
      else {
        markers.push({ id: id, latitude: lat, longitude: lng })
      }
      this.getmapCtx().addMarkers({ markers, clear: true, complete(ecomplete) { } })

      this.setData({ polylines: this.data.polylines })
      if (updateaddr !== false) {
        this.getaddrlist({ lat: lat, lng: lng })
      }


    },

    onSearch() {
      var searchkey = this.data.searchkey
      if (searchkey) {
        var that = this;
        locationclient.search(searchkey).then(function (xdata) {
          that.setData({ addrlist: xdata.data })
          that.selecteditem({ currentTarget: { dataset: { idx: 0 } } })
        })
      }

    },
    onsearchChange(ev) {

      this.setData({ searchkey: ev.detail })

    },
    selecteditem(ev) {
      var dataset = ev.currentTarget.dataset
      var idx = dataset.idx

      var addmodel = this.data.addrlist[idx]

      var that = this

      that.data.isoping = true
      setTimeout(() => {
        that.data.isoping = false
      }, 1000);

      var intracity = this.data.intracity
      var distance = null
      if (this.data.mode == 2) {
        distance = acttoolv2.distanceByLnglat(addmodel.location.lng, addmodel.location.lat, intracity.lng, intracity.lat)
      }

      //acttoolv2
      this.setData({ distance, selectidx: idx, latitude: addmodel.location.lat, longitude: addmodel.location.lng })
      if (this.data.mode == 2) {
        this.updatepolylines(addmodel.location.lat, addmodel.location.lng, 2, false)
      }
      else {
        this.movemark(2, addmodel.location.lat, addmodel.location.lng)
      }


    },
    loadcircle(intracity) {
      var that = this;
      var circles = [];

      var circle = this.getcirclemodel(intracity["lat"], intracity["lng"], intracity["maxdistance"])

      circles.push(circle)

      var temmdoel = that.getempmark(1);

      var polylines = [];
      var polyline = { points: [], width: 10 }
      temmdoel.latitude = parseFloat(circle["latitude"])

      temmdoel.longitude = parseFloat(circle["longitude"])

      polyline.points.push({ latitude: parseFloat(circle["latitude"]), longitude: parseFloat(circle["longitude"]) }, { latitude: parseFloat(circle["latitude"]), longitude: parseFloat(circle["longitude"]) })
      polylines.push(polyline)

      this.data.polylines = polylines
      temmdoel["title"] = ""
      temmdoel["label"] = ""
      temmdoel["width"] = "0"
      temmdoel["height"] = "0"
      temmdoel["customCallout"] = { display: "ALWAYS" }
      var markers = []
      markers.push(temmdoel);
      this.setData({ circles, markers })

    },
    onClickButton() {
      var selctmodel = this.data.addrlist[this.data.selectidx];
      var fomatmodel = {
        province: selctmodel.ad_info.province,
        city: selctmodel.ad_info.city,
        county: selctmodel.ad_info.district,
        countycode: selctmodel.ad_info.adcode,
        addrname: selctmodel.title,
        addrinfo: selctmodel.address,
        lat: selctmodel.location.lat,
        lng: selctmodel.location.lng,
      }


      this.triggerEvent("selected", fomatmodel)
      this.Backfunc();  
    }
  }
})
